﻿
using System.FileServer.ApiModels;

using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace System.FileServer
{
    /// <summary>
    /// 文件服务
    /// </summary>
    [ApiController]
    [Route("system/[controller]")]
    public class FileServer : GCCAPIControllerBase
    {
        public FileServer(AbsGCCContext context) : base(context)
        {
        }

        /// <summary>
        /// 创建文件,可以传输多个,服务会自动甄别file信息
        /// </summary>
        /// <param name="formInfos">文件信息</param>
        /// <returns></returns>
        [HttpPost("items")]
        public DataResponse<List<CreateFilesResponse>> CreateFiles(IFormCollection files)
        {
            var insertRes = FileManager.Instance.SaveFiles(files.Files, out var dbModels);
            if (!insertRes)
            {
                return SystemError<List<CreateFilesResponse>>();
            }

            var res = dbModels.Select(item => new CreateFilesResponse(item)).ToList();
            return HandleData(res);
        }

        /// <summary>
        /// 使用校验码查询某
        /// </summary>
        /// <param name="checkCode">校验码</param>
        /// <returns></returns>
        [HttpGet("items/checkCode/{checkCode}")]
        public DataResponse<List<GetFilesByCheckCodeResponse>> GetFilesByCheckCode([FromRoute] string checkCode)
        {
            return HandleData(FileManager.Instance.SearchByCheckCode(checkCode).Select(item => new GetFilesByCheckCodeResponse(item)).ToList());
        }

        /// <summary>
        /// 使用校验码查询某
        /// </summary>
        /// <param name="checkCode">校验码</param>
        /// <returns></returns>
        [HttpGet("items/fid/{fid}")]
        public DataResponse<GetFileByIDResponse> GetFileByID([FromRoute] long fid)
        {
            var res = FileManager.Instance.SearchByID(fid);
            if (res is null)
            {
                return SystemError<GetFileByIDResponse>();
            }
            return HandleData(new GetFileByIDResponse(res));
        }

        /// <summary>
        /// 使用校验码查询某
        /// </summary>
        /// <param name="request">分页请求</param>
        /// <returns></returns>
        [HttpGet("items")]
        public DataResponse<List<GetAllItemsResponse>> GetAllItems([FromQuery] GetAllItemsRequest request)
        {
            if (request is null || request.PageSize > 100)
            {
                return IllegalRequest<List<GetAllItemsResponse>>();
            }
            return HandleData(
                FileManager.Instance.SearchItems(request, out var count).Select(item => new GetAllItemsResponse(item)).ToList()
                , count);
        }


    }
}
